import React, { useState, useRef } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { authService } from '../../services/auth';
import Toast from '../../components/Toast';
import ptLogo from '../../assets/pt-logo.png';
import './Login.css';

const Register = () => {
  const navigate = useNavigate();
  const [step, setStep] = useState(1); // 1: 邮箱验证 2: 填写注册信息
  const [email, setEmail] = useState('');
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [form, setForm] = useState({ username: '', password: '', verificationCode: '', invitationCode: '' });
  
  // 添加引用以支持回车键功能
  const emailInputRef = useRef(null);
  const usernameInputRef = useRef(null);
  const passwordInputRef = useRef(null);
  const codeInputRef = useRef(null);
  const inviteCodeInputRef = useRef(null);

  const showToastMessage = (message) => {
    setToastMessage(message);
    setShowToast(true);
  };

  //邮箱验证
  const handleSendVerificationCode = async (e) => {
    e.preventDefault();
    if (!email) {
      showToastMessage('请输入邮箱地址');
      return;
    }
    setLoading(true);
    try {
      const response = await authService.sendVerificationCode(email, 'email_verification');
      if (response.data.code === 200) {
        showToastMessage('验证码已发送至您的邮箱，请查收');
        setStep(2);
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown(prev => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        showToastMessage(response.data.message || '发送验证码失败');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '发送验证码失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理邮箱输入框回车事件
  const handleEmailKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSendVerificationCode(e);
    }
  };

  // 处理注册表单回车事件
  const handleKeyDown = (e, field) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      if (field === 'username') {
        passwordInputRef.current.focus();
      } else if (field === 'password') {
        codeInputRef.current.focus();
      } else if (field === 'code') {
        inviteCodeInputRef.current.focus();
      } else if (field === 'invite') {
        handleRegister(e);
      }
    }
  };

  //注册信息填写
  const handleRegister = async (e) => {
    e.preventDefault();
    if (!form.username || !form.password || !form.verificationCode) {
      showToastMessage('请填写完整信息');
      return;
    }
    setLoading(true);
    try {
      const data = {
        username: form.username,
        email,
        password: form.password,
        verificationCode: form.verificationCode,
        invitationCode: form.invitationCode,
      };
      const response = form.invitationCode
        ? await authService.register(data)
        : await authService.registerOpen(data);
      if (response.data.code === 200) {
        showToastMessage('注册成功，正在跳转...');
        setTimeout(() => navigate('/login'), 1200);
      } else {
        showToastMessage(response.data.message || '注册失败，请重试');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '注册失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-bg">
      <div className="login-card">
        <div className="login-header">
          <img src={ptLogo} alt="PT" className="pt-logo" />
          <span className="pt-title">PT种子站</span>
        </div>
        <div className="login-form">
          <h2>用户注册</h2>
          {step === 1 && (
            <form onSubmit={handleSendVerificationCode}>
              <div className="input-group">
                <label className="input-label">邮箱</label>
                <input
                  className="input-box"
                  type="email"
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  onKeyDown={handleEmailKeyDown}
                  ref={emailInputRef}
                  required
                  placeholder="请输入邮箱"
                />
              </div>
              <button className="login-btn" type="submit" disabled={loading || countdown > 0}>
                {loading ? '发送中...' : countdown > 0 ? `${countdown}秒后重试` : '发送验证码'}
              </button>
              <div className="login-links" style={{ justifyContent: 'center' }}>
                <Link to="/login">已有账号？立即登录</Link>
              </div>
            </form>
          )}
          {step === 2 && (
            <form onSubmit={handleRegister}>
              <div className="input-group">
                <label className="input-label">邮箱</label>
                <input
                  className="input-box"
                  type="email"
                  value={email}
                  disabled
                />
              </div>
              <div className="input-group">
                <label className="input-label">用户名</label>
                <input
                  className="input-box"
                  type="text"
                  value={form.username}
                  onChange={e => setForm(f => ({ ...f, username: e.target.value }))}
                  onKeyDown={(e) => handleKeyDown(e, 'username')}
                  ref={usernameInputRef}
                  required
                  pattern="[a-zA-Z0-9_-]{3,50}"
                  placeholder="请输入用户名"
                />
              </div>
              <div className="input-group">
                <label className="input-label">密码</label>
                <input
                  className="input-box"
                  type="password"
                  value={form.password}
                  onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
                  onKeyDown={(e) => handleKeyDown(e, 'password')}
                  ref={passwordInputRef}
                  required
                  placeholder="请输入密码"
                />
              </div>
              <div className="input-group">
                <label className="input-label">验证码</label>
                <input
                  className="input-box"
                  type="text"
                  value={form.verificationCode}
                  onChange={e => setForm(f => ({ ...f, verificationCode: e.target.value }))}
                  onKeyDown={(e) => handleKeyDown(e, 'code')}
                  ref={codeInputRef}
                  required
                  placeholder="请输入邮箱收到的验证码"
                />
              </div>
              <div className="input-group">
                <label className="input-label">邀请码（选填）</label>
                <input
                  className="input-box"
                  type="text"
                  value={form.invitationCode}
                  onChange={e => setForm(f => ({ ...f, invitationCode: e.target.value }))}
                  onKeyDown={(e) => handleKeyDown(e, 'invite')}
                  ref={inviteCodeInputRef}
                  placeholder="请输入邀请码（如有）"
                />
              </div>
              <button className="login-btn" type="submit" disabled={loading}>
                {loading ? '注册中...' : '注册'}
              </button>
              <div className="login-links" style={{ justifyContent: 'center' }}>
                <Link to="/login">已有账号？立即登录</Link>
              </div>
            </form>
          )}
        </div>
      </div>
      
      {showToast && (
        <Toast 
          message={toastMessage} 
          onClose={() => setShowToast(false)} 
        />
      )}
    </div>
  );
};

export default Register; 